//给定一个排序链表，删除所有重复的元素，使得每个元素只出现一次。 
//
// 示例 1: 
//
// 输入: 1->1->2
//输出: 1->2
// 
//
// 示例 2: 
//
// 输入: 1->1->2->3->3
//输出: 1->2->3 
// Related Topics 链表

package leetcode.editor.cn;
public class RemoveDuplicatesFromSortedList {

    public static void main(String[] args) {
        Solution solution = new RemoveDuplicatesFromSortedList().new Solution();
        ListNode listNode = constructList(new int[]{1,1,2,3,3});
        ListNode node = solution.deleteDuplicates(listNode);
        printList(node);
    }

    static ListNode constructList(int[] array) {
        if (array == null || array.length == 0) {
            return null;
        }

        ListNode head = null;
        ListNode tail = null;
        for (int i = 0; i < array.length; i++) {
            if (head == null) {
                head = new ListNode(array[i]);
                tail = head;
            } else {
                ListNode node = new ListNode(array[i]);
                tail.next = node;
                tail = node;
            }
        }

        return head;
    }

    static void printList(ListNode node) {
        if (node == null) {
            return;
        }

        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }

        System.out.println("-------------------end ");
    }
    
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return null;
        }

        ListNode p = head;
        ListNode prev = null;
        while (p != null) {
            if (prev == null) {
                prev = p;
                p = p.next;
                continue;
            }

            if (prev.val == p.val) {
                // 删除自己
                prev.next = p.next;
                p = p.next;
                continue;
            }

            prev = p;
            p = p.next;
        }

        return head;
    }


}
//leetcode submit region end(Prohibit modification and deletion)
public static class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
}